package com.lct.eq2.util;

import java.io.*;
import java.net.*;
import com.lct.eq2.gui.GetNewVersion;

public class FileDownload {
    GetNewVersion parent;

    public FileDownload() {
        this.parent = null;
    }

    public FileDownload(GetNewVersion parentVersion) {
        this.parent = parentVersion;
    }
    
    public void download(String address, String localFileName) {
        if (parent != null) {
            parent.setStatus("Downloading...");
        }
        OutputStream out = null;
        URLConnection conn = null;
        InputStream  in = null;
        try {
            URL url = new URL(address);
            out = new BufferedOutputStream(
                    new FileOutputStream(localFileName));
            
            in = url.openStream();
            int max = in.available();
            if (parent != null) {
                parent.setProgressMax(max);
            }

            byte[] buffer = new byte[1024];
            int numRead;
            long numWritten = 0;
            while ((numRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, numRead);
                numWritten += numRead;
                if (parent != null) {
                    parent.setProgress(numWritten);
                }
                
            }
            if (parent != null) {
                parent.setProgress(max);
                parent.setStatus("Download finished.");
            }
            //System.out.println(localFileName + "\t" + numWritten);
        } catch (Exception exception) {
            exception.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException ioe) {
            }
        }
    }
    
    public void download(String address) {
        int lastSlashIndex = address.lastIndexOf('/');
        if (lastSlashIndex >= 0 &&
                lastSlashIndex < address.length() - 1) {
            download(address, address.substring(lastSlashIndex + 1));
        } else {
            System.err.println("Could not figure out local file name for " +
                    address);
        }
    }
}